from bs4 import BeautifulSoup  # 网页解析，获取数据
import re  # 正则表达式，进行文字匹配
import urllib.request
import urllib.error  # 制定URL，获取网页数据
import xlwt  # 进行Excel操作
import sqlite3  # 进行sqlite数据库操作

findLink = re.compile(r'<a href="(.*?)">')  # 影片详情链接正则
findImgSrc = re.compile(r'<img.*src="(.*?)">', re.S)  # re.S让换行符包含在字符中
findTitle = re.compile(r'<span class="title">(.*)</span>')  # 影片片名
findRating = re.compile(
    r'<span class="rating_num" property="v:average">(.*)</span>')  # 影片评分
findJudge = re.compile(r'<span>(\d*)人评价</span>')  # 评价人数
findInq = re.compile(r'<span class="inq">(.*)</span>')  # 影片概述
findBd = re.compile(r'<p class="">(.*?)</p>', re.S)  # 影片相关内容


# 得到一个指定URL网页的内容
def askURL(url):
    head = {  # 模拟浏览器头部信息，向豆瓣服务器发送消息
        # 用户代理，告诉豆瓣服务器，我们是什么机器、浏览器
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36"
    }
    request = urllib.request.Request(url, headers=head)
    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode('utf-8')
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)

    return html


def getData(baseurl):
    datalist = []
    for i in range(0, 10):  # 调用10次网页信息页面，一次25个电影
        url = baseurl+str(i*25)
        html = askURL(url)  # 保存获取到的网页源码

        # 2.逐一解析数据
        soup = BeautifulSoup(html, "html.parser")
        for item in soup.find_all('div', class_="item"):  # 查找符合要求的字符串，形成列表
            data = []  # 保存一部电影item所有信息
            item = str(item)

            link = re.findall(findLink, item)[0]  # 影片详情链接
            data.append(link)

            imgSrc = re.findall(findImgSrc, item)[0]  # 影片海报
            data.append(imgSrc)

            titles = re.findall(findTitle, item)  # 影片片名
            if len(titles) == 2:
                ctitle = titles[0]
                data.append(ctitle)  # 添加中文片名
                otitle = titles[1].replace("/", "")  # 去掉无关的符号
                data.append(otitle)  # 添加外国片名
            else:
                data.append(titles[0])  # 添加中文片名
                data.append(' ')  # 添加空外国片名

            rating = re.findall(findRating, item)[0]  # 影片评分
            data.append(rating)

            judgeNum = re.findall(findJudge, item)[0]  # 评价人数
            data.append(judgeNum)

            inq = re.findall(findInq, item)  # 影片概述
            if len(inq) != 0:
                inq = inq[0].replace("。", "")  # 去掉句号
                data.append(inq)
            else:
                data.append(" ")  # 留空

            bd = re.findall(findBd, item)[0]  # 影片相关内容
            bd = re.sub('<br(\s+)?/>(\s+)?', " ", bd)  # 去掉<br/>
            bd = re.sub('/', " ", bd)  # 替换/
            data.append(bd.strip())  # 去掉前后的空格

            datalist.append(data)

    return datalist


def saveData(datalist, savePath):
    workbook = xlwt.Workbook(encoding='utf-8', style_compression=0)
    Worksheet = workbook.add_sheet('豆瓣电影TOP250', cell_overwrite_ok=True)
    col = ("电影详情链接", "电影图片链接", "影片中文名", "影片外国名",
           "影片评分", "评分人数", "影片概述", "影片相关内容")
    for i in range(0, 8):
        Worksheet.write(0, i, col[i])
    for i in range(0, 250):
        print("第%d条" % (i+1))
        data = datalist[i]
        for j in range(0, 8):
            Worksheet.write(i+1, j, data[j])

    workbook.save(savePath)


def main():
    baseurl = "https://movie.douban.com/top250?start="
    # 1.爬取网页
    datalist = getData(baseurl)
    # 3.保存数据
    savePath = "豆瓣电影TOP250.xls"
    saveData(datalist, savePath)


if __name__ == "__main__":
    main()
    print("爬取完毕！")
